package com.aliyun.messagemgt.web.controller;

import com.aliyun.messagemgt.application.service.MessageTemplateService;
import com.aliyun.messagemgt.application.service.OperateLogService;
import com.aliyun.messagemgt.common.constants.MgtCommonConst;
import com.aliyun.messagemgt.common.enums.OperateTypeEnum;
import com.aliyun.messagemgt.common.enums.ResourceTypeEnum;
import com.aliyun.messagemgt.common.errorcode.CommonErrorCode;
import com.aliyun.messagemgt.common.exceptions.BaseException;
import com.aliyun.messagemgt.dto.MessageTemplate;
import com.aliyun.messagemgt.dto.OperateLog;
import com.aliyun.messagemgt.dto.query.MessageTemplateQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @Description
 * @Author hzw
 * @Date 2020/12/17 11:01
 * @Version 1.0
 */
@Api(tags = "消息模板相关接口")
//@CrossOrigin
@RestController
@RequestMapping("/messageTemplate")
public class MessageTemplateController {

    @Autowired
    private MessageTemplateService messageTemplateService;

    @Autowired
    private OperateLogService operateLogService;

    @Deprecated
    @ApiOperation(value = "发布/下线消息模板")
    @PostMapping("/offLine")
    public Object templateOffLine(@RequestBody MessageTemplate add) {
        MessageTemplateQuery query = new MessageTemplateQuery();
        query.setTemplateId(add.getTemplateId());
        MessageTemplate messageTemplate = messageTemplateService.templateDetail(query);
        if(messageTemplate == null){
            throw new BaseException(CommonErrorCode.FAIL_UPDATE_TEMPLATE);
        }
        String sourceName = messageTemplate.getTemplateName();
        OperateLog operateLog = new OperateLog()
                .setOperateResourceType(ResourceTypeEnum.TEMPLATE.getCode())
                .setModule(MgtCommonConst.MODULE_SMART_PUSH)
                .setOperateUser(add.getUserId())
                .setOperateUserName(add.getUserName())
                .setOperateDept(add.getDepartment())
                .setOperateDeptName(add.getDepartmentName())
                .setOperateTime(new Date())
                .setOperateResourceId(Math.toIntExact(add.getTemplateId()))
                .setOperateResourceName(sourceName);
        int i = 0;
        try {
            operateLog.setOperateType(OperateTypeEnum.OFFLINE.getCode());
            i = (int)messageTemplateService.templateModify(add);
            if(i <= 0){
                operateLog.setFailMsg(CommonErrorCode.FAIL_OFFLINE_TEMPLATE.errName());
                operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
            }else{
                operateLog.setFailMsg(CommonErrorCode.SUCCESS_OFFLINE_TEMPLATE.errName());
                operateLog.setOperateStatus(MgtCommonConst.OPERATER_SUCCESS);
            }
        }catch (Exception e){
            operateLog.setFailMsg(CommonErrorCode.FAIL_OFFLINE_TEMPLATE.errName());
            operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
            if(e instanceof BaseException){
                throw e;
            }else{
                e.printStackTrace();
                throw new RuntimeException("操作失败！");
            }
        }finally {
            operateLogService.insertOperateLog(operateLog);
        }
        return i;
    }
    @ApiOperation(value = "消息模板列表")
    @PostMapping("/list")
    @ResponseBody
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = MessageTemplate.class)
    )
    public Object msgTemplateList(@RequestBody MessageTemplateQuery query) {
        return messageTemplateService.queryList(query);
    }

    @ApiOperation(value = "消息模板列表")
    @PostMapping("/isEnabledList")
    @ResponseBody
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = MessageTemplate.class)
    )
    public Object isEnabledList(@RequestBody MessageTemplateQuery query) {
        return messageTemplateService.isEnabledList(query);
    }


    @ApiOperation(value = "删除消息模板")
    @DeleteMapping("/delete")
    public Object templateDelete(@RequestBody MessageTemplateQuery query) {
        MessageTemplate messageTemplate = messageTemplateService.templateDetail(query);
        if(messageTemplate == null){
            throw new BaseException(CommonErrorCode.FAIL_UPDATE_TEMPLATE);
        }
        String sourceName = messageTemplate.getTemplateName();
        OperateLog operateLog = new OperateLog()
                .setOperateResourceType(ResourceTypeEnum.TEMPLATE.getCode())
                .setModule(MgtCommonConst.MODULE_SMART_PUSH)
                .setOperateUser(query.getUserId())
                .setOperateUserName(query.getUserName())
                .setOperateDept(query.getDepartment())
                .setOperateDeptName(query.getDepartmentName())
                .setOperateTime(new Date())
                .setOperateResourceId(Math.toIntExact(query.getTemplateId()))
                .setOperateResourceName(sourceName);
        int i = 0;
        try {
            operateLog.setOperateType(OperateTypeEnum.DEL.getCode());
            i = (int)messageTemplateService.templateDelete(query);
            if(i <= 0){
                operateLog.setFailMsg(CommonErrorCode.FAIL_DELETE_TEMPLATE.errName());
                operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
            }else{
                operateLog.setFailMsg(CommonErrorCode.SUCCESS_DELETE_TEMPLATE.errName());
                operateLog.setOperateStatus(MgtCommonConst.OPERATER_SUCCESS);
            }
        }catch (Exception e){
            operateLog.setFailMsg(CommonErrorCode.FAIL_DELETE_TEMPLATE.errName());
            operateLog.setOperateStatus(MgtCommonConst.OPERATER_FAIL);
            if(e instanceof BaseException){
                throw e;
            }else{
                throw new RuntimeException("操作失败！");
            }
        }finally {
            operateLogService.insertOperateLog(operateLog);
        }
        return i;
    }

    @ApiOperation(value = "消息模板详情")
    @PostMapping("/detail")
    @ResponseBody
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = MessageTemplate.class)
    )
    public Object detail(@RequestBody MessageTemplateQuery query) {
        return messageTemplateService.templateDetail(query);
    }

    @ApiOperation(value = "保存消息模板和模板参数")
    @PostMapping("/saveTemplate")
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = MessageTemplate.class)
    )
    public Object saveTemplate(@RequestBody MessageTemplate messageTemplateParam){
        if (messageTemplateParam.getTemplateCode() == null){
            throw new BaseException(CommonErrorCode.COMMON_PARAM_INVALID);
        }
        messageTemplateService.checkTemplate(messageTemplateParam);
        return messageTemplateService.saveTemplate(messageTemplateParam);
    }

    @ApiOperation(value = "更新消息模板和模板参数")
    @PostMapping("/updateTemplate")
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = MessageTemplate.class)
    )
    public Object updateTemplate(@RequestBody MessageTemplate messageTemplateParam){
        if (messageTemplateParam.getTemplateId() == null){
            throw new BaseException(CommonErrorCode.COMMON_PARAM_INVALID);
        }
        messageTemplateService.checkTemplate(messageTemplateParam);
        return messageTemplateService.updateTemplate(messageTemplateParam);
    }

    @ApiOperation(value = "启停用")
    @PostMapping("/updateStatus")
    @ResponseBody
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = MessageTemplate.class)
    )
    public Object updateStatus(@RequestBody MessageTemplate messageTemplate){
        if (messageTemplate.getTemplateId() == null || messageTemplate.getIsEnabled() == null){
            throw new BaseException(CommonErrorCode.COMMON_PARAM_INVALID);
        }
        return messageTemplateService.updateStatus(messageTemplate);
    }

    @ApiOperation(value = "逻辑删除")
    @PostMapping("/isDelete")
    @ResponseBody
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = MessageTemplate.class)
    )
    public Object isDelete(@RequestBody MessageTemplate templateParam){
        if (templateParam.getTemplateId() == null || templateParam.getIsDeleted() == null){
            throw new BaseException(CommonErrorCode.COMMON_PARAM_INVALID);
        }
        return messageTemplateService.isDelete(templateParam);
    }
}
